package com.demo.function.excel.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.demo.function.excel.easyexcel.pojo.ExtraInfo;
import com.demo.function.excel.easyexcel.pojo.ValidateResult;
import org.apache.commons.collections4.CollectionUtils;

import org.hibernate.validator.HibernateValidator;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

public class ValidateListener<T> implements ReadListener<T> {

    private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(false)
            .buildValidatorFactory().getValidator();

    private boolean validate;
    private ValidateResult<T> result = new ValidateResult<>();

    public ValidateListener(boolean validate) {
        this.validate = validate;
    }

    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        if (!validate) {
            result.getSuccessList().add(data);
            return;
        }

        Set<ConstraintViolation<T>> violations = validator.validate(data);
        if (CollectionUtils.isEmpty(violations)) {
            result.getSuccessList().add(data);
            return;
        }

        for (ConstraintViolation<T> violation : violations) {
            if (data instanceof ExtraInfo) {
                ExtraInfo extraInfo = (ExtraInfo) data;
                extraInfo.addErrorMsg(violation.getMessage());
            }
        }
        result.getFailList().add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    public ValidateResult<T> getValidateResult() {
        return this.result;
    }
}
